package com.yh.zz_hlj.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yh.zz_hlj.AppConfig;
import com.yh.zz_hlj.AppContext;
import com.yh.zz_hlj.R;
import com.yh.zz_hlj.api.RetrofitSingleton;
import com.yh.zz_hlj.base.BaseFragment;
import com.yh.zz_hlj.common.CyptoUtils;
import com.yh.zz_hlj.common.PLog;
import com.yh.zz_hlj.common.StringUtils;
import com.yh.zz_hlj.modules.adatper.CKAdapter;
import com.yh.zz_hlj.modules.bean.CKInfo;
import com.yh.zz_hlj.modules.bean.Result;
import com.yh.zz_hlj.modules.listener.HidingScrollListener;
import com.yh.zz_hlj.modules.ui.LoginActivity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import butterknife.ButterKnife;
import butterknife.InjectView;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class CKUndoFragment extends BaseFragment {

    @InjectView(R.id.recyclerview)
    RecyclerView mRecyclerView;
    @InjectView(R.id.one_clock)
    TextView one_clock;
    @InjectView(R.id.one_code)
    TextView one_code;
    @InjectView(R.id.ll_one)
    LinearLayout ll_one;
    @InjectView(R.id.one_temp)
    TextView one_temp;
    @InjectView(R.id.one_humidity)
    TextView one_humidity;
    @InjectView(R.id.one_wind)
    TextView one_wind;

    CKAdapter mAdapter;

    String  retoken;
    List <CKInfo> orgInfos = new ArrayList<>();
    List <CKInfo> doInfos = new ArrayList<>();
    List <CKInfo> ckedInfos = new ArrayList<>();
    Set<String> selected;
    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_rkdetail, container, false);
        ButterKnife.inject(this, view);
        initView(view);
        initData();
        return view;
    }

    @Override
    public void initView(View view) {
        //recclerview
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.addOnScrollListener(new HidingScrollListener() {
            @Override
            public void onHide() {

            }

            @Override
            public void onShow() {

            }
        });
        one_clock.setText("单号");
        one_temp.setText("发货时间");
        one_humidity.setText("工程名称");
        one_wind.setText("是否出库");
        one_code.setText("订单号");
        ll_one.setVisibility(View.VISIBLE);
    }

    @Override
    public void initData() {
        selected=new HashSet<>();
        fetchWorkData();
    }

    @Override
    public void onClick(View v) {
        final int id = v.getId();
        switch (id) {
            case R.id.rl_check_update:
                break;
            default:
                break;
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        int index_menu = 0;
        index_menu = R.menu.send_menu;
        inflater.inflate(index_menu, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.send_btn:
                showWaitDialog();
                if (mAdapter != null) {
                    List <CKInfo> mcinfos = mAdapter.getWorkInfos();
                    ArrayList <CKInfo> checkedCKS = new ArrayList<>();
                    if (mcinfos.size() == 0) {
                        Snackbar.make(mRecyclerView, "未选中任何内容", Snackbar.LENGTH_SHORT).show();
                        hideWaitDialog();
                    } else {
                        String mStr = "";
                        Set<String> mSet=new HashSet<>();
                        Set<String> mNoSet=new HashSet<>();
                        for (int j=0;j<mcinfos.size();j++) {
                            CKInfo  info=mcinfos.get(j);
                            if (info.getFwgtype()) {
                                if (info != null) {
                                    if (!checkedCKS.contains(info)) {
                                        boolean f=info.getFwgtype();
                                        if (f){
                                            //获得选择的行
                                                for (int i = 0; i < orgInfos.size(); i++) {
                                                    CKInfo infb = orgInfos.get(i);
                                                    if (infb!=null) {
                                                        String innBill=infb.getFBillNo();
                                                        if (!StringUtils.isEmpty(innBill)){
                                                            if (innBill.equals(info.getFBillNo())){
                                                                checkedCKS.add(infb);
                                                                mSet.add(info.getCustomerName());
                                                                mNoSet.add(infb.getFInterID()+"");
                                                            }
                                                        }
                                                    }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        if (mSet.size()==1) {
                            Iterator i = mNoSet.iterator();//先迭代出来
                            int mmindex=0;
                            while(i.hasNext()){//遍历
                                String str = i.next().toString();
                                String ms = "'" + str + "'";
                                String ms1 = str;
                                if (mmindex == mNoSet.size() - 1) {
                                    mStr += ms;
                                } else {
                                    mStr += ms + ",";
                                }
                                mmindex++;
                            }
                            //判断当前是手机还是PDA
//                            UIHelper.showScanActivity(mActivity, mStr,checkedCKS,"出库扫码");
//                                 UIHelper.showCKDan(mActivity,checkedCKS, null);
                        }else if  (mSet.size()>1) {
                            Snackbar.make(mRecyclerView, "只能选中一个客户的发货通知单", Snackbar.LENGTH_SHORT).show();
                            hideWaitDialog();
                        }else if  (mSet.size()<1) {
                            Snackbar.make(mRecyclerView, "至少选中一个客户的发货通知单", Snackbar.LENGTH_SHORT).show();
                            hideWaitDialog();
                        }
                    }
                } else {
                    mActivity.finish();
                    ;
                }
                break;
        }
        return true;
    }

    private void fetchWorkData() {
        String private_token = AppContext.getInstance().getProperty(AppConfig.PRIVATE_TOKEN);
        if (StringUtils.isEmpty(private_token)) {
            Snackbar.make(mRecyclerView, "登录过期，请重新登录", Snackbar.LENGTH_SHORT).show();
            Intent intent = new Intent(getActivity(), LoginActivity.class);
            startActivity(intent);
        } else {
            retoken = CyptoUtils.decode(AppConfig.key, private_token);
            showWaitDialog("获取待出库列表...");
            RetrofitSingleton.getApiService(mActivity).
                    CKS(retoken)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(observer);
        }
    }

    Observer<Result> observer = new Observer<Result>() {
        @Override
        public void onCompleted() {
            PLog.d("s", "onCompleted");
            hideWaitDialog();
        }

        @Override
        public void onError(Throwable e) {
            PLog.d("s", e.getMessage());
            Snackbar.make(mRecyclerView, e.getMessage(), Snackbar.LENGTH_SHORT).show();
            hideWaitDialog();
        }

        @Override
        public void onNext(Result result) {
            if (result != null) {
                Object objects = result.getData();
                String message = result.getMessage();
                if (StringUtils.isEmpty(message)) {
                    message = "未获得待出库的单据";
                }
                if (objects != null) {
                    Gson gson = new Gson();
                    String json = gson.toJson(objects);
                    ArrayList<CKInfo> xxxxs = gson.fromJson(json, new TypeToken<ArrayList<CKInfo>>() {}.getType());
                    if (xxxxs != null) {
                        if (xxxxs.size() > 0) {
                            orgInfos.clear();
                            ckedInfos.clear();
                            for (int i = 0; i < xxxxs.size(); i++) {
                                CKInfo infb = xxxxs.get(i);
                                if (infb!=null && !StringUtils.isEmpty(infb.getFEntrySelfS0241())) {
                                    orgInfos.add(infb);
                                    selected.add(infb.getFBillNo());
                                }
                            }

                            //去掉重复行
                            for (String str:selected) {
                                for (int i = 0; i < orgInfos.size(); i++) {
                                    CKInfo infb = orgInfos.get(i);
                                    if (infb!=null) {
                                        String innBill=infb.getFBillNo();
                                        if (!StringUtils.isEmpty(innBill)){
                                            if (innBill.equals(str)){
                                                doInfos.add(infb);
                                                i=orgInfos.size();
                                            }
                                        }
                                    }
                                }
                            }

                            if (doInfos.size()>0){
                                setHasOptionsMenu(true);
                            }else {
                                setHasOptionsMenu(false);
                                Snackbar.make(mRecyclerView, "还没有待出库的单据!", Snackbar.LENGTH_SHORT).show();
                            }

                            //排序
                            // 按倒序
                            Collections.sort(doInfos, new Comparator<CKInfo>() {
                                public int compare(CKInfo arg0, CKInfo arg1) {
                                    int hits0 = arg0.getFInterID();
                                    int hits1 = arg1.getFInterID();
                                    if (hits1 > hits0) {
                                        return 1;
                                    } else if (hits1 == hits0) {
                                        return 0;
                                    } else {
                                        return -1;
                                    }
                                }
                            });

                            mAdapter = new CKAdapter(mActivity, doInfos);
                            mRecyclerView.setAdapter(mAdapter);
                            hideWaitDialog();
                        } else {
                            Snackbar.make(mRecyclerView, message, Snackbar.LENGTH_SHORT).show();
                            hideWaitDialog();
                        }
                    } else {
                        Snackbar.make(mRecyclerView, message, Snackbar.LENGTH_SHORT).show();
                        hideWaitDialog();
                    }
                } else {
                    Snackbar.make(mRecyclerView, message, Snackbar.LENGTH_SHORT).show();
                    hideWaitDialog();
                }
            }
        }
    };
}
